import { createRouter, createWebHistory } from 'vue-router'
import Login from './views/Login.vue'
import { useUserStore } from '@/store/user';

// 所有路由
const staticRoutes = [
  { path: '/', redirect: '/home' },
  { path: '/login', component: Login }
];

const router = createRouter({
  history: createWebHistory(),
  routes: staticRoutes,
});

router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();
    if (!userStore.token && to.path !== '/login') {
        return next('/login');
    }
    if (userStore.token && !userStore.routesAdded) {
        await userStore.loadUserData();
        return next(to.fullPath);
    }
    next();
})

export default router;